package com.mingqijia.gassafety.job.job.mbp;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.mingqijia.gassafety.db.entity.*;
import com.mingqijia.gassafety.db.entity.vo.UserServiceComboVO;
import com.mingqijia.gassafety.db.entity.vo.WorkOrderServiceVO;
import com.mingqijia.gassafety.db.mapper.FieldTemplateMapper;
import com.mingqijia.gassafety.db.mapper.ServiceComboDetailMapper;
import com.mingqijia.gassafety.db.mapper.ServiceComboMapper;
import com.mingqijia.gassafety.db.mapper.ServiceComboOrderMapper;
import com.mingqijia.gassafety.job.feign.ConsoleSkFeignClient;
import com.mingqijia.gassafety.job.request.mbp.ConsoleSkUpdateRequest;
import com.mingqijia.gassafety.job.request.sk.ConsoleSkRecordsRequest;
import com.mingqijia.gassafety.job.response.ConsoleSkUpdateResponse;
import com.mingqijia.gassafety.job.response.sk.ConsoleSkRecordsList;
import com.mingqijia.gassafety.job.response.sk.ConsoleSkRecordsResponse;
import com.mingqijia.gassafety.job.service.ServiceComboOrderService;
import com.mingqijia.gassafety.job.service.WorkOrderHistoryService;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.UrlConst;
import com.mingqijia.gassafety.shared.response.HuiShengCommentlistResp;
import com.mingqijia.gassafety.shared.response.HuiShengCommentlistVo;
import com.mingqijia.gassafety.shared.service.HuiShengService;
import com.mingqijia.gassafety.shared.utils.HttpUtil;
import com.mingqijia.gassafety.shared.utils.commonUtils.DateUtils;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: duanhongxiang
 * @Desc:
 * @create: 2024-09-05 13:50
 **/
@Component
@Slf4j
public class WorkOrderHuiShengJob {

    @Autowired
    private WorkOrderHistoryService workOrderHistoryService;

    @Autowired
    private HuiShengService huiShengService;

    @Autowired
    private ServiceComboMapper serviceComboMapper;

    @Autowired
    private ServiceComboOrderService serviceComboOrderService;

    @Autowired
    private ConsoleSkFeignClient consoleSkFeignClient;


    @XxlJob("workOrderHuiSheng")
    public ReturnT<String> workOrderHuiSheng(String param) {
        XxlJobLogger.log("XXLJOB-workOrderHuiSheng start..." );
        log.info("workOrderHuiSheng ---- start:");
        try {
            workOrderHuiShengHandle(param);
        } catch (Exception e) {
            log.info("workOrderStatus-error:{}", e);
        }

        XxlJobLogger.log("XXLJOB-workOrderHuiSheng end..." );
        log.info("workOrderHuiSheng end.:");
        return ReturnT.SUCCESS;
    }

    private void workOrderHuiShengHandle(String param){
        //查询 工单状态,并更新
        List<WorkOrderServiceVO> orderServiceVOS = serviceComboMapper.selectOrder();
        log.info("workOrderHuiShengHandle-list:{}",JSONObject.toJSONString(orderServiceVOS));
        if (CollectionUtils.isNotEmpty(orderServiceVOS)) {
            //根据单号进行转map
            Map<String, String> orderNoMap = orderServiceVOS.stream().collect(Collectors.toMap(WorkOrderServiceVO::getOrderNo, WorkOrderServiceVO::getAlarmRecordId));
            //根据手机号进行分组查询
            Map<String, List<WorkOrderServiceVO>> listMap = orderServiceVOS.stream().collect(Collectors.groupingBy(WorkOrderServiceVO::getPhone));
            for (String phone : listMap.keySet()) {
                List<WorkOrderServiceVO> workOrderServiceVOS = listMap.get(phone);
                StringBuilder sb = new StringBuilder();
                for (WorkOrderServiceVO serviceVO : workOrderServiceVOS) {
                    sb.append(serviceVO.getOrderNo()).append(",");
                }
                String token = huiShengService.login(phone);
                Map<String, Object> params = new HashMap<>();
                params.put("order_sn", sb.toString());
                params.put("page", 1);
                params.put("pagesize", workOrderServiceVOS.size());
                params.put("token", token);
                String getlist = huiShengService.getlist(params);
                if (StringUtils.isNotEmpty(getlist)) {
                    HuiShengCommentlistResp commentlistResp = JSONObject.parseObject(getlist, HuiShengCommentlistResp.class);
                    for (HuiShengCommentlistVo shengCommentlistVo : commentlistResp.getList()) {
                        if ("2".equals(shengCommentlistVo.getStatus()) || "3".equals(shengCommentlistVo.getStatus()) || "10".equals(shengCommentlistVo.getStatus())) {
                            if (orderNoMap.containsKey(shengCommentlistVo.getOrder_sn())) {
                                ConsoleSkUpdateRequest consoleSkUpdateRequest = new ConsoleSkUpdateRequest();
                                consoleSkUpdateRequest.setId(orderNoMap.get(shengCommentlistVo.getOrder_sn()));
                                consoleSkUpdateRequest.setDealStatus(3);
                                consoleSkUpdateRequest.setResult("完成");
                                log.info("alarmSOSUpdate-request:{}",JSONObject.toJSONString(consoleSkUpdateRequest));
                                ConsoleSkUpdateResponse consoleSkUpdateResponse = consoleSkFeignClient.alarmSOSUpdate(consoleSkUpdateRequest);
                                log.info("alarmSOSUpdate-consoleSkUpdateResponse:{}",JSONObject.toJSONString(consoleSkUpdateResponse));
                            }
                            Map<String, Object> ext = new HashMap<>();
                            ext.put("serviceEndTime", shengCommentlistVo.getFws_end_time());
                            ext.put("visitPerson", shengCommentlistVo.getStaff_name());
                            ext.put("contact", shengCommentlistVo.getAddress().getPhone_mob());
                            ext.put("serviceBeginTime", shengCommentlistVo.getFws_start_time());
                            LambdaUpdateWrapper<ServiceComboOrder> updateWrapper = new LambdaUpdateWrapper<>();
                            updateWrapper.or().eq(ServiceComboOrder::getThirdOrderNo, shengCommentlistVo.getOrder_sn())
                                    .set(ServiceComboOrder::getThirdOrderId, shengCommentlistVo.getOrder_id())
                                    .set(ServiceComboOrder::getThirdOrderStatus, shengCommentlistVo.getStatus())
                                    .set(ServiceComboOrder::getThirdOrderExt, JSONObject.toJSONString(ext))
                                    .set(ServiceComboOrder::getThirdOrderServicerName, shengCommentlistVo.getStaff_name())
                                    .set(ServiceComboOrder::getThirdOrderServicerPhone, shengCommentlistVo.getAddress().getPhone_mob());
                            if (StringUtils.isNotEmpty(shengCommentlistVo.getFws_start_time())) {
                                updateWrapper.set(ServiceComboOrder::getThirdOrderServiceBeginTime, shengCommentlistVo.getFws_start_time());
                            }
                            if ("3".equals(shengCommentlistVo.getStatus())) {
                                updateWrapper.set(ServiceComboOrder::getOrderstatus, 1);
                            } else {
                                updateWrapper.set(ServiceComboOrder::getOrderstatus, 2);
                            }
                            serviceComboOrderService.update(updateWrapper);
                            LambdaQueryWrapper<WorkOrderHistory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                            lambdaQueryWrapper.eq(WorkOrderHistory::getOrderNo,shengCommentlistVo.getOrder_sn()).eq(WorkOrderHistory::getIsDeleted,0);
                            WorkOrderHistory workOrderHistory = new WorkOrderHistory();
                            workOrderHistory.setHandleStatus(1);
                            workOrderHistory.setCompleteTime(DateUtils.formatDateStandard(shengCommentlistVo.getNeed_time()));
                            workOrderHistoryService.update(workOrderHistory,lambdaQueryWrapper);
                        }

                    }
                }
            }
        }
    }
}
